<template>
  <div class="real_time" :id="id"></div>
</template>

<script setup lang="tsx">
import { onMounted, reactive, ref, useId } from 'vue';
import { realDataChart } from '@/utils';
import { useEventSource } from '@boeyo/hooks';
import { useUserStore } from '@boeyo/portal';

const userStore = useUserStore();
interface Props {
  /** 设备标识 */
  code: string;
  /** 格值 */
  latticeValue?: number;
  /** 烈度 */
  intensity?: number;
  /** 采样率 */
  samplingRate?: number;
}
const {
  code,
  latticeValue = 500,
  intensity = 1,
  samplingRate = 100,
} = defineProps<Props>();

const id = useId();

const formatData = (cb) => {
  let data = {};
  const checkData = () => {
    let flag = false;
    if (Object.keys(data).length !== 3) return false;
    Object.values(data)
      .map((item) => item[0][0])
      .reduce((prev, cur) => {
        flag = prev === cur;
        return cur;
      });
    return flag;
  };
  const push = (_data) => {
    Object.keys(_data).forEach((_key) => {
      let key;
      switch (_key) {
        case 'Z':
          key = 'EIZ';
          break;
        case 'N':
          key = 'EIN';
          break;
        case 'E':
          key = 'EIE';
          break;
        default:
          break;
      }
      if (_key !== 'X') {
        data[key] = _data[_key];
      }
    });
    if (checkData()) {
      cb(data);
      data = {};
    }
  };
  return push;
};
const dataInfo = ref({});

const push = formatData((data) => {
  dataInfo.value = data;
  console.time('chart render time');
  const dataSource = {};
  for (const key in data) {
    if (Object.prototype.hasOwnProperty.call(data, key)) {
      const element = data[key];
      dataSource[key] = element.map((item) => {
        item[1] = item[1];
        return item;
      });
    }
  }
  renderChart(dataSource);
  console.timeEnd('chart render time');
});

let renderChart;
const random = Math.random().toString().slice(-6);
const { connect } = useEventSource(`/api/edge/sse/300/${random}/${code}`, {
  headers: {
    ['Authorization']: `Bearer ${userStore.token}`,
    'Content-Type': 'application/json',
    Accept: '*/*',
  },
  withCredentials: false,
  onMessage(res) {
    const data = JSON.parse(res);
    push(data);
  },
});

onMounted(() => {
  renderChart = realDataChart({
    target: document.getElementById(id),
    title: `设备标识：${1} | 采样率：${1} | 烈度：${1}`,
    direction: 'vertical',
    channels: [
      {
        name: 'EIN',
        color: '#77E3F9',
        yName: '单位: 度(°)',
        grid: {
          show: true,
          top: '10%',
          containLabel: true,
        },
      },
      // { name: 'EIZ', color: '#F16995', yName: '单位: 度(°)' },
      // { name: 'EIE', color: '#DFC428', yName: '单位: 度(°)' },
    ],
  });
  connect();
});
</script>

<style lang="scss" scoped>
.real_time {
  width: 100%;
  height: 400px;
}
</style>
